package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.utils.MD5;
import com.atguigu.srb.core.constants.CommonConstants;
import com.atguigu.srb.core.entity.UserAccount;
import com.atguigu.srb.core.entity.UserInfo;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.service.UserAccountService;
import com.atguigu.srb.core.service.UserInfoService;
import com.atguigu.srb.core.vo.RegisterVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author ccy
 * @since 2025-04-09
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {



    @Resource
    private UserAccountService userAccountService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterVO registerVO) {

        //判断用户是否被注册
        LambdaQueryWrapper<UserInfo> qW = Wrappers.lambdaQuery();
        qW.eq(UserInfo::getMobile, registerVO.getMobile());
        if (this.count(qW) > 0) {
            //MOBILE_EXIST_ERROR(-207, "手机号已被注册")
            Assert.isTrue(false, ResponseEnum.MOBILE_EXIST_ERROR);
        }

        //插入用户基本信息
        UserInfo userInfo = UserInfo.builder()
                .userType(registerVO.getUserType())
                .nickName(registerVO.getMobile())
                .name(registerVO.getMobile())
                .mobile(registerVO.getMobile())
                .password(MD5.encrypt(registerVO.getPassword()))
                .status(CommonConstants.STATUS_NORMAL)
                .headImg("https://srb-file.oss-cn-beijing.aliyuncs.com/avatar/07.jpg")
                .build();

        this.save(userInfo);

        //创建会员账号
        UserAccount userAccount = UserAccount.builder()
                .userId(userInfo.getId())
                .build();

        this.userAccountService.save(userAccount);

    }
}
